package com.wsfk.ssm.service;

import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.List;

import javax.annotation.Resource;

import maps.com.wsfk.ssm.user.PictureMapper;
import org.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;

import org.springframework.stereotype.Service;
import org.apache.tools.zip.ZipOutputStream;

import com.wsfk.ssm.entity.HandBook;
import com.wsfk.ssm.entity.Picture;
import com.wsfk.ssm.entity.User;
import com.wsfk.ssm.entity.Zip;
import com.wsfk.ssm.path.CallPath;
import com.wsfk.ssm.path.POPS;
import com.wsfk.ssm.path.SiteUtil;
import com.wsfk.ssm.tools.Pagination;

@Service("PictureSvcImpl")
public class PictureSvcImpl implements PictureSvc {

	Logger log = Logger.getLogger(this.getClass());

	private PictureMapper pictureMapper;
	private HandBookSvc handBookSvc;

	
	
	private FileSvc fileSvc;

	private POPS pops;
	

	public POPS getPops() {
		return pops;
	}
	@Resource
	public void setPops(POPS pops) {
		this.pops = pops;
	}

	@Resource
	public void setPictureMapper(PictureMapper pictureMapper) {
		this.pictureMapper = pictureMapper;
	}
	@Resource
	public void setHandBookSvc(HandBookSvc handBookSvc) {
		this.handBookSvc = handBookSvc;
	}

	public int addPicture(List<Picture> pictures) {
		int i = 0;
		for (Picture picture : pictures) {
			i += pictureMapper.addPicture(picture);
		}
		return i;
	}

	public int updateByStatus(String id, String createStatus) {
		return pictureMapper.updateByStatus(id, createStatus);
	}

	// zip可以删除
	public void zip(String inputFileName) {
		try {
			System.out.println(inputFileName);
			String zipFileName = inputFileName + ".zip";
			System.out.println(zipFileName);

			File inputFile = new File(inputFileName);
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
					zipFileName));
			zip(out, inputFile, "");
			out.close();
		} catch (FileNotFoundException e) {
			log.error("can't write to " + e);
			e.printStackTrace();
		} catch (Exception e) {
			log.error("can't write to " + e);
			e.printStackTrace();
		}
	}

	// 可以删除
	protected void zip(ZipOutputStream out, File f, String base) {
		try {
			if (f.isDirectory()) {
				File[] fl = f.listFiles();
				out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
				base = base.length() == 0 ? "" : base + "/";
				for (int i = 0; i < fl.length; i++) {
					zip(out, fl[i], base + fl[i].getName());
				}
			} else {
				out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
				FileInputStream in = new FileInputStream(f);
				int b;
				while ((b = in.read()) != -1) {
					out.write(b);
				}
				in.close();
			}
		} catch (IOException e) {
			log.error("can't write to " + e);
			e.printStackTrace();
		}
	}

	public int addZip(Zip zip) {
		return pictureMapper.addZip(zip);
	}

	protected String querySite() {
		String apache = SiteUtil.querySite();
		return apache;
	}

	// 查询手册中的图片
	public List<Picture> queryAllPicByBook(String handBookId) {
		if (StringUtils.isBlank(handBookId)) {
			return null;
		} else {
			return pictureMapper.queryAllPicByBook(handBookId);
		}
	}

	public Pagination queryPagePicByBook(String handBookId, Pagination page) {
		List<Picture> list = pictureMapper.queryPagePicByBook(handBookId,
				String.valueOf(page.getStartRow()),
				String.valueOf(page.getEndRow()));
		int totalCount = pictureMapper.queryPagePicCountByBookId(handBookId);
		page.setTotalCount(totalCount);
		page.setData(list);
		return page;
	}
/*
	// 修改图片
	public void updatePic(File upload, String uploadFileName, String picFileDir) {
		try {
			String picName = picFileDir
					.substring(picFileDir.lastIndexOf("/") + 1);
			String picPath = picFileDir.substring(0,
					picFileDir.lastIndexOf("/"));
			String booksDir = querySite().substring(0,
					querySite().lastIndexOf("/"));
			File file = new File(booksDir + "/" + picPath);
			File f = new File(file, picName);
			f.createNewFile();
			FileUtils.copyFile(upload, f);
		} catch (IOException e) {
			log.error("can't write to " + e);
			e.printStackTrace();
		}
	}
*/
	public int queryPagePicCountByBookId(String handBookId) {
		return pictureMapper.queryPagePicCountByBookId(handBookId);
	}

	public int savePicture(Picture picture) {
		return pictureMapper.addPicture(picture);
	}
/*
	public Picture saveOnePicFile(File upload, int count, HandBook handBook,
			String userName) {
		Picture picture = new Picture();
		try {
			String booksDir = querySite().substring(
					querySite().lastIndexOf("/") + 1);
			String bookId = handBook.getId();
			String bookPath = querySite() + "/" + userName + "/" + "book"
					+ bookId;
			String path = bookPath + "/images";
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			File f = new File(file, count + ".jpg");
			f.createNewFile();
			FileUtils.copyFile(upload, f);
			picture.setId(UUID.randomUUID().toString());
			picture.setType(Picture.CONTENT);
			picture.setFileDir(booksDir + "/" + userName + "/" + "book"
					+ bookId + "/images/" + count + ".jpg");
			picture.setHandBookId(bookId);
			savePicture(picture);
			updateByStatus(bookId, HandBook.UNFINISHED);
		} catch (IOException e) {
			log.error("can't write to " + e);
			e.printStackTrace();
		}
		return picture;
	}
*/
	@Override
	public HandBook queryBookById(String id) {
		return pictureMapper.queryBookById(id);
	}

	@Override
	public User queryUserById(String id) {
		return pictureMapper.queryUserById(id);
	}

	public boolean savePicFile(User user, HandBook book, List<File> uploadPic,
			List<String> place) {
		try {
			fileSvc.saveContent(user, book, uploadPic, place);
			List<String> picPath = new CallPath().imageWay(user, book).builds();
			for (int i = 0; i < picPath.size(); i++) {
				Picture picture = Picture.getInstance(book.getId(),
						picPath.get(i));
				pictureMapper.addPicture(picture);
			}
			pictureMapper.updateByStatus(book.getId(), HandBook.UNFINISHED);
		} catch (IOException e) {
			log.error("File upload problems" + e);
			throw new RuntimeException(e);
		}
		return true;
	}

	@Resource
	public void setFileSvc(FileSvc fileSvc) {
		this.fileSvc = fileSvc;
	}

	public boolean updatePic(User user, HandBook book, String picId, File upload) {
		try {

			Picture pic = pictureMapper.queryPictureById(picId);
			String picPath = new CallPath().savePre(pops).picWay(pic).build();
			fileSvc.saveContent(upload, pic);
			
		} catch (IOException e) {
			log.error("File upload problems"+e);
			throw new RuntimeException(e);
		}
		return true;
	}
	public boolean updateIcon(User user, HandBook book, String picId, File upload) {
		try {
			Picture picture = pictureMapper.queryPictureById(picId);
			
			fileSvc.updateIcon(picture, upload);
			
		} catch (IOException e) {
			log.error("File upload problems"+e);
			throw new RuntimeException(e);
		}
		return true;
	}
	
	
	
}
